package com.omenkk.juc.c3;

import com.omenkk.juc.util.Slepper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;
@Slf4j
public class demo3 {
    //版本号api
  static  AtomicStampedReference<String> ref=new AtomicStampedReference<>("A",0);
    public static void main(String[] args) {
        String prev=ref.getReference();
        int stamp = ref.getStamp();
        log.debug("版本号:{}",stamp);
        other();
        Slepper.sleep(2);
        log.debug("change:{} A->C，版本号:{}",ref.compareAndSet(prev,"C",stamp,stamp+1),ref.getStamp());
    }

    private static void other() {
        new Thread(()->{
            String prev=ref.getReference();
            int stamp = ref.getStamp();
            log.debug("change:{} A->B",ref.compareAndSet(prev,"B",stamp,stamp+1));
        },"t1").start();
        Slepper.sleep(1);
        new Thread(()->{
            String prev=ref.getReference();
            int stamp = ref.getStamp();
            log.debug("change:{} B->A",ref.compareAndSet(prev,"A",stamp,stamp+1));
        },"t2").start();
    }

}
